package com.alpha.dao;

import java.sql.SQLException;
import java.util.ArrayList;

import javax.naming.NamingException;

import com.alpha.dao.interfaces.ICategoryDao;


public class CategoryDao extends AlphaDao implements ICategoryDao{
	
	public ArrayList<String> retrieveAllCategories() throws SQLException, NamingException{
		ArrayList<String> categories = new ArrayList<String>();
		this.connect();
		try {
			String select = "SELECT * FROM tbl_category";
			this.statement = this.connection.createStatement();
			this.resultSet = this.statement.executeQuery(select);
			while(this.resultSet.next()) {
				String name = this.resultSet.getString("category_name");
				categories.add(name);
			}
		} catch (SQLException e) {
			logger.error(e.getMessage());
			throw e;
		} finally {
			this.disconnect();
		}
		return categories;
	}
	
	public int retrieveCategoryId(String categoryName) throws SQLException, NamingException{
		int id = -1;
		this.connect();
		try {
			String select = "SELECT * FROM tbl_category";
			this.statement = this.connection.createStatement();
			this.resultSet = this.statement.executeQuery(select);
			while(this.resultSet.next()) {
				String name = this.resultSet.getString("category_name");
				if(name.equalsIgnoreCase(categoryName)){
					id = this.resultSet.getInt("category_id");
				}
			}
		} catch (SQLException e) {
			logger.error(e.getMessage());
			throw e;
		} finally {
			this.disconnect();
		}
		return id;
	}
	
	public boolean insertCategory(String category) throws NamingException, SQLException {
		boolean success = false;
		this.connect();
		String insert = "INSERT INTO tbl_category(category_name) VALUES(?)";
		try {
			this.preparedStatement = this.connection.prepareStatement(insert);
			this.preparedStatement.setString(1, category);
			
			int rows = this.preparedStatement.executeUpdate(); 
			if(rows > 0) {
				success = true;
			}
		} catch (SQLException e) {
			logger.error(e.getMessage());
			throw e;
		} finally {
			this.disconnect();
		}
		
		return success;
	}
	
}
